package src;

// CopyFileUsingByteStream.java: Copy files
import java.io.*;
import javax.swing.JOptionPane;

public class CopyFileUsingByteStream {

  
  public static void main(String[] args) {
    // Declare input and output file streams
    FileInputStream fis = null;
    FileOutputStream fos = null;

	//get user input
	String f1 = JOptionPane.showInputDialog("Enter File You Want To Copy From");
	String f2= JOptionPane.showInputDialog("Enter File You Want To Copy To");

    try {
      //create an object representing the file you want to copy from
      File copyFromFile = new File(f1);
      
      // Create file input stream to read from the file you want to copy from
      fis = new FileInputStream(copyFromFile);
      
      //create an object representing the file you want to copy to
      File copyToFile = new File(f2);
      
      //If the file you want to copy to exists, then don't allow the overwrite to take place
      if (copyToFile.exists()) {
        JOptionPane.showMessageDialog(null, "file " + copyToFile+ " already exists");
        return;
      }//end if
      else {
         // Create file output stream to write to the file you want to copy to
        fos = new FileOutputStream(copyToFile);
      }//end else

      
      // Continuously read a byte from fis and write it to fos
      int r;
      
      while ((r = fis.read()) != -1) {
      
      	fos.write((byte)r);
      
      }//end while
      
      JOptionPane.showMessageDialog(null, "The copy has been successfull");
    
    }//end try
    catch (FileNotFoundException ex) {
      	JOptionPane.showMessageDialog(null, "File not found: " + f1);
    }//end catch
    
    catch (IOException ex){
    	JOptionPane.showMessageDialog(null,ex.getMessage());	
    }//end catch
    
    finally {
      try {
        // Close files
        if (fis != null) fis.close();
        if (fos != null) fos.close();
      }//end try
      catch (IOException ex) {
        JOptionPane.showMessageDialog(null, ex.toString());
      }//end catch
  
    }//end finally
  
  }//end main

}//end class
